package com.kaifamiao.jdbc.d0908;

import com.kaifamiao.jdbc.d0908.entity.Users;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Demo02 {

    public static void main(String[] args) {
//        QueryRunner
//        DataSource dataSource = new MysqlDataSource();

        QueryRunner runner = new QueryRunner();

        String url = "jdbc:mysql://localhost:3306/kfm";
        String user = "root";
        String password = "";
        Connection connection = DBUtil.getConnection(url, user, password);
        String sql = "select * from users";
        try {
            List<Users> list = runner.query(connection, sql, new ResultSetHandler<List<Users>>() {

                @Override
                public List<Users> handle(ResultSet resultSet) throws SQLException {
                    List<Users> list = new ArrayList<>();
                    while (resultSet.next()){
                        Users users = new Users();
                        users.setId(resultSet.getInt("id"));
                        users.setUsername(resultSet.getString("username"));
                        users.setPassword(resultSet.getString("password"));
//                        users.setCreateDate(resultSet.getDate("createDate"));
                        users.setGender(resultSet.getInt("gender"));

                        list.add(users);
                    }
                    return list;
                }
            });

            list.forEach(e -> System.out.println(e));

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


}
